import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# 设置中文字体（防止图像乱码）
matplotlib.rcParams['font.family'] = 'SimHei'

# 数据准备
data = {
    "date": [
        "2022-01", "2022-02", "2022-03", "2022-04", "2022-05", "2022-06", "2022-07", "2022-08", "2022-09", "2022-10", "2022-11", "2022-12",
        "2023-01", "2023-02", "2023-03", "2023-04", "2023-05", "2023-06", "2023-07", "2023-08", "2023-09", "2023-10", "2023-11", "2023-12",
        "2024-01", "2024-02", "2024-03", "2024-04", "2024-05", "2024-06", "2024-07", "2024-08", "2024-09", "2024-10", "2024-11", "2024-12"
    ],
    "temp": [
        0.1, 1.68, 9.13, 16.67, 22.39, 24.4, 28.32, 28.23, 24.6, 16.52, 12.1, 1.32,
        1.61, 4.11, 11.0, 16.27, 22.35, 27.03, 28.9, 29.16, 26.93, 20.81, 9.47, 1.45,
        1.1, 1.86, 9.74, 17.97, 23.55, 26.83, 28.55, 30.39, 25.8, 18.26, 12.1, 3.52
    ]
}

df = pd.DataFrame(data)

# 归一化
scaler = MinMaxScaler()
scaled_temp = scaler.fit_transform(np.array(df['temp']).reshape(-1, 1))

# 序列构建
def create_dataset(dataset, time_step=12):
    X, y = [], []
    for i in range(len(dataset) - time_step):
        X.append(dataset[i:(i+time_step), 0])
        y.append(dataset[i + time_step, 0])
    return np.array(X), np.array(y)

time_step = 12
X, y = create_dataset(scaled_temp, time_step)
X = X.reshape(X.shape[0], X.shape[1], 1)

# 建模
model = Sequential([
    tf.keras.Input(shape=(time_step, 1)),
    LSTM(50, return_sequences=True),
    LSTM(50),
    Dense(1)
])
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, y, epochs=100, batch_size=4, verbose=0)

# 预测未来6个月
future_input = scaled_temp[-time_step:].reshape(1, time_step, 1)
future_forecast = []

for _ in range(6):
    next_pred = model.predict(future_input, verbose=0)
    next_pred_reshaped = next_pred.reshape(1, 1, 1)
    future_input = np.append(future_input[:, 1:, :], next_pred_reshaped, axis=1)
    future_forecast.append(next_pred[0, 0])

forecast_inverse = scaler.inverse_transform(np.array(future_forecast).reshape(-1,1))
predict_months = ['2025-01','2025-02','2025-03','2025-04','2025-05','2025-06']

# 实际温度
actual_temp = [1.45, 2.32, 10.61, 16.37, 20.52, 26.57]

# 保存预测CSV
output_df = pd.DataFrame({
    '日期(年月)': predict_months,
    '预测平均最高气温(℃)': forecast_inverse.flatten()
})
output_df.to_csv('monthly_avg_temp_2025_predict.csv', index=False, encoding='utf-8-sig')
print("预测已保存：monthly_avg_temp_2025_predict.csv")

# 可视化对比
plt.figure(figsize=(10, 5))
plt.plot(predict_months, forecast_inverse.flatten(), marker='o', label='预测气温', linestyle='--', color='orange')
plt.plot(predict_months, actual_temp, marker='o', label='实际气温', linestyle='-', color='blue')

plt.title('2025年上半年平均最高气温：预测 vs 实际')
plt.xlabel('月份')
plt.ylabel('平均最高气温 (℃)')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
